﻿
namespace storge
{
	using System;
	using System.IO;
	using System.Runtime.InteropServices;

	public class WindowsRecycleBin : IRecycleFiles
	{
		public void Recycle(IFolder folder)
		{
			WindowsRecycleBin.Accept(folder.Path);
		}

		public void Recycle(IFile file)
		{
			WindowsRecycleBin.Accept(file.Path);
		}

		private static void Accept(string path)
		{
			if (File.Exists(path) || Directory.Exists(path))
			{
				SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
				shf.wFunc = FO_DELETE;
				shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
				shf.pFrom = path + "\0";

				int value = NativeMethods.SHFileOperation(ref shf);
			}
		}

		#region Native Win32 API

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
		private struct SHFILEOPSTRUCT
		{
			public IntPtr hwnd;
			[MarshalAs(UnmanagedType.U4)]
			public int wFunc;
			public string pFrom;
			public string pTo;
			public short fFlags;
			[MarshalAs(UnmanagedType.Bool)]
			public bool fAnyOperationsAborted;
			public IntPtr hNameMappings;
			public string lpszProgressTitle;
		}

		const int FO_DELETE = 3;
		const int FOF_ALLOWUNDO = 0x40;
		const int FOF_NOCONFIRMATION = 0x10;

		/// <summary>
		/// WinAPI functions
		/// </summary>        
		private static class NativeMethods
		{
			[DllImport("shell32.dll", CharSet = CharSet.Auto)]
			public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
		}

		#endregion
	}
}

